package com.sz.virtualbank.web.interceptor;

import com.sz.virtualbank.common.annotation.LoginRequired;
import com.sz.virtualbank.common.constant.CommonConstants;
import com.sz.virtualbank.common.exception.BusinessException;
import com.sz.virtualbank.dao.entity.User;
import com.sz.virtualbank.service.user.UserService;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

/**
 * 登录拦截器
 * 
 * @author Claude
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    
    @Autowired
    private UserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是处理方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取处理方法上的LoginRequired注解
        LoginRequired loginRequired = handlerMethod.getMethodAnnotation(LoginRequired.class);
        
        // 如果没有LoginRequired注解，或者不需要登录，直接通过
        if (loginRequired == null || !loginRequired.value()) {
            return true;
        }
        
        // 获取token
        String token = getTokenFromCookie(request);
        
        // 如果token为空，抛出未登录异常
        if (StringUtils.isBlank(token)) {
            throw BusinessException.of(4001, "未登录或登录已过期");
        }
        
        try {
            // 验证token
            User user = userService.getCurrentUser(token);
            if (user == null) {
                throw BusinessException.of(4001, "未登录或登录已过期");
            }
        } catch (Exception e) {
            throw BusinessException.of(4001, "未登录或登录已过期");
        }
        
        return true;
    }
    
    /**
     * 从Cookie中获取Token
     * 
     * @param request HTTP请求
     * @return Token
     */
    private String getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (CommonConstants.COOKIE_NAME.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        
        // 尝试从请求头中获取Token
        String token = request.getHeader(CommonConstants.TOKEN_HEADER);
        if (StringUtils.isNotBlank(token) && token.startsWith(CommonConstants.TOKEN_PREFIX)) {
            return token.substring(CommonConstants.TOKEN_PREFIX.length());
        }
        
        return null;
    }
}
